import { StandardData } from 'api/interface/iot/StandardData';
import { Subject, Subscription } from 'rxjs';

const iotData = new Subject();
const scopSubjects: Map<string, Subscription> = new Map();
export enum IotDataType {
  //标准数据
  standardData = 'standardData',
  // 实时列表
  realTimeList = 'realTimeList',
  // 报警数据
  alarmData = 'alarmData',
}
export type IotDataStruct = {
  type: IotDataType;
  data: StandardData;
};

/**
 *  发布标准数据
 * @param data
 */
export const pubStandardData = (data: StandardData) => {
  iotData.next({
    type: IotDataType.standardData,
    data,
  });
};

/**
 * 订阅标准数据
 * @param callback
 * @param scopeName
 */
export const subStandardData = (scopeName: string, callback: (data: StandardData) => void) => {
  const unSub = iotData.subscribe((data) => {
    const _data = data as IotDataStruct;
    if (_data.type === IotDataType.standardData) {
      callback(_data?.data);
    }
  });
  console.log('订阅标准数据', scopeName);
  scopSubjects.set(scopeName, unSub);
};

/**
 * 取消订阅
 * @param scopeName  作用域名称
 */
export const unSubStandardData = (scopeName: string) => {
  const unSub = scopSubjects.get(scopeName);
  if (unSub) {
    console.log('取消订阅', scopeName);
    unSub.unsubscribe();
    scopSubjects.delete(scopeName);
  }
};

export default iotData;
